<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-04-12 18:48:24
 * @Description  : 内部协作分享的panel
-->

<template>
  <div class="share-to-con" v-loading="loading">
    <div class="header flex items-center justify-center">
      <div class="left-avator mr-3">
        <SvgIcon icon="folder-share" size="80px"></SvgIcon>
      </div>
      <div class="share-info">
        <div class="title flex items-center">
          <h3 class="text-primaryColor mr-2">协作分享</h3>
          <n-tag :bordered="false" type="info"> {{ shareInfo.title }} </n-tag>
        </div>
        <div class="path text-[13px] mt-2 text-[#aaa]">
          <span class="font-bold">所在位置：</span>
          <span>{{ shareInfo.path }}</span>
        </div>
        <div class="desc text-[13px] mt-2 text-[#aaa]">
          <span class="font-bold">分享时间：</span>
          <span class="text-gray">{{ formatTime(shareInfo.createTime) }}</span>
        </div>
      </div>
    </div>
    <n-divider class="!my-2" />

    <div class="actions flex justify-between mb-2">
      <div class="flex items-center">
        <left-line></left-line>选择协作分享的部门或用户
      </div>
      <n-popselect
        trigger="click"
        :options="[]"
        class="w-[300px]"
        display-directive="show"
        placement="right"
      >
        <template #header>
          <user-select
            :canSelectDep="true"
            @change-value="handleUserChange"
            :default-user-ids="targetList.map((item) => item.id)"
          ></user-select>
        </template>
        <template #empty> <div></div> </template>
        <n-button class="flex items-center">
          <i class="iconfont icon-tianjiatianjiayonghu11 mr-1"></i>
          添加用户或部门
        </n-button>
      </n-popselect>
    </div>
    <AuthTable
      :target-list="targetList"
      :size-max-column="false"
      @change-target-list="handleChangeTargetList"
      @change-default-role-id="handleChangeDefaultRoleId"
    ></AuthTable>

    <!-- 权限详情 -->
    <div class="flex text-[13px] text-[#bcc4d0] mt-2">
      分享给对方或对方所在部门后，用户可以在[分享给我的]中看到。
      <div
        class="flex hover:(bg-[#def]) text-[#13b1fe] cursor-pointer"
        @click="openDocAuthTable"
      >
        <SvgIcon icon="jinggao" color="#13b1fe"></SvgIcon>
        了解文档协作权限
      </div>
    </div>

    <n-form
      class="p-2"
      ref="formRef"
      :label-width="80"
      :label-placement="menuShow ? 'left' : 'top'"
      label-align="right"
      :model="shareInfo"
      size="small"
      require-mark-placement="left"
    >
      <n-form-item label="到期时间：" path="openDeadLine">
        <n-switch
          :value="shareInfo.openDeadLine === '1'"
          @update:value="
            (value: boolean) => (shareInfo.openDeadLine = '' + +value)
          "
        />
        <div class="ml-[12px] text-gray-400 text-[12px]">
          开启并设置后，超过时间分享自动失效
        </div>
      </n-form-item>
      <my-transition>
        <div v-if="shareInfo.openDeadLine === '1'">
          <n-form-item path="deadline" label=" ">
            <n-date-picker
              v-model:value="shareInfo.deadline"
              type="datetime"
              clearable
            />
          </n-form-item>
        </div>
      </my-transition>
    </n-form>

    <n-divider class="!my-2" />
    <div class="footer flex justify-end items-center">
      <n-button type="tertiary" @click="handleToCancelShare">取消分享</n-button>
      <n-button
        class="mx-2 grent-btn"
        type="primary"
        @click="handleToUpdateShare"
      >
        复制&保存
      </n-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useMessage, useDialog } from 'naive-ui'
import userUserStore from '@/stores/modules/user'
import type { IndexObj } from '@/types/commom'
import { getSourceById } from '@/api/source'
import { cancelShare, createShare, updateShare } from '@/api/share'
import { formatTime } from '@/utils'
import { load } from '@/utils/loading'
import { userMenuShow } from '@/hooks/useMenuShow'

const userStore = userUserStore()

const props = defineProps<{
  sourceId: string
}>()

const emits = defineEmits<{
  (e: 'open-doc-auth'): void
  (e: 'close'): void
}>()

const message = useMessage()
const dialog = useDialog()
const { menuShow } = userMenuShow()

const targetList = ref<IndexObj[]>([])
const authTableDefaultRoleId = ref('4')

const handleChangeTargetList = (list: IndexObj[]) => {
  targetList.value = list
}

// 用户或者部门选择发生了改变
const handleUserChange = (value: string | string[], depsInfo: IndexObj[]) => {
  // 选择的对象发生了改变，[a,b,c]---->[a,b,f,g,h]
  // 权限信息同步修改，a，b的暂时不需要变更（authRolen）

  // targetList保留 value还在的，其他删除
  // target原先没有的，进行添加

  // console.log(depsInfo, 'depsInfo')

  targetList.value = targetList.value.filter((item) => {
    return value.includes(item.id)
  })

  // target现在没有的
  let moreTargets = depsInfo
    .filter((item) => {
      return !targetList.value.some((item2) => {
        return item2.id === item.id
      })
    })
    .map((item3) => {
      return {
        authRole: authTableDefaultRoleId.value,
        ...item3,
        targetName: item3.name || item3.username,
        pTargetName: item3.parent ? item3.parent.name : '',
        targetType: item3.username ? '1' : '2'
      }
    })

  targetList.value = targetList.value.concat(moreTargets)
}

const handleChangeDefaultRoleId = (value: string) => {
  authTableDefaultRoleId.value = value
}

const openDocAuthTable = () => {
  emits('open-doc-auth')
}

const loading = ref(false)

const shareInfo = reactive({
  id: '',
  title: '',
  openDeadLine: '0',
  deadline: Date.now(),
  authTo: [],
  path: '',
  createTime: ''
})

const getLabelName = (id: string, label: string) => {
  if (id === userStore.userInfo?.rootSourceId) {
    return '个人空间'
  }
  return label
}

// 根据ID查询文件详情
const loadSourceInfo = () => {
  loading.value = true
  getSourceById({ sourceId: props.sourceId })
    .then((res) => {
      if (!res.data) {
        return message.warning('资源ID有误')
      }
      if (!res.data.Share) {
        // 创建一个share
        shareInfo.title = res.data.filename
        createShare({
          title: res.data.filename,
          sourceId: res.data.id
        }).then(() => {
          loadSourceInfo()
        })
      } else {
        // 进行值的更新
        const { title, deadline, createTime, id } = res.data.Share
        shareInfo.id = id
        shareInfo.title = title
        shareInfo.deadline = +deadline === 0 ? Date.now() : +deadline
        shareInfo.openDeadLine = +deadline === 0 ? '0' : '1'
        shareInfo.createTime = createTime
        shareInfo.path = res.data.pathInfo
          .map((item) => getLabelName(item.id, item.filename))
          .join('/')
        shareInfo.authTo = res.data.Share.ShareTos
        // targetList.value = []
        targetList.value = res.data.Share.ShareTos.map((item: any) => {
          return {
            targetType: +item.targetType,
            targetId: item.targetId,
            id: item.targetId,
            authRole: item.roleId,
            targetName:
              +item.targetType === 1
                ? item.User.username
                : item.Department.name,
            avator: +item.targetType === 1 ? item.User.avator : ''
          }
        })
      }
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadSourceInfo()
})

// 更新share
const handleToUpdateShare = () => {
  // console.log(targetList.value, 'targetList')
  load.show()
  updateShare({
    shareId: shareInfo.id,
    title: shareInfo.title,
    isShareTo: 1,
    deadline:
      shareInfo.openDeadLine === '1' ? '' + shareInfo.deadline : undefined,
    authTo: targetList.value.map((item) => {
      return {
        targetType: +item.targetType,
        targetId: item.id,
        roleId: item.authRole
      }
    })
  })
    .then(() => {
      message.success('操作成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

// 取消分享share
const handleToCancelShare = () => {
  dialog.warning({
    title: '提示',
    content: '你确定要取消该分享吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      load.show()
      cancelShare({
        shareIds: [shareInfo.id],
        type: 1
      })
        .then(() => {
          message.success('操作成功')
          afterOpt()
        })
        .catch(console.error)
        .finally(() => {
          load.hide()
        })
    },
    onNegativeClick: () => {}
  })
}

const afterOpt = () => {
  emits('close')
}
</script>

<style scoped lang="scss"></style>
